package com.sinaapp.kjWeb.Schedule;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.annotation.Resource;

import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import com.sinaapp.kjWeb.action.Action;
import com.sinaapp.kjWeb.action.CheckInAction;
import com.sinaapp.kjWeb.action.CheckOutAction;
import com.sinaapp.kjWeb.action.HackLoginAction;
import com.sinaapp.kjWeb.pojo.KaiJieUser;
import com.sinaapp.kjWeb.service.KjEmployService;
import com.sinaapp.kjWeb.util.ConfigUtils;

/*
 *auth:徐疆
 *date 2014-1-25 下午4:11:44
 */

@Service("atuoSchedule")
public class AtuoSchedule implements InitializingBean {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(AtuoSchedule.class);
	
	private Timer KJtimer = new Timer();
	@Resource(name="DefaultRunTime")
	private RunTimeStrategy rtStrategy;
	
	@Resource(name="kjEmployService")
	private KjEmployService kjs;
	
	public void addAtuoTask(KaiJieUser kju){
		String sw=ConfigUtils.getInstance().getValueAndDefault("kj_auto_on_off", "0");
		if("1".equals(sw)){
			KJtimer.schedule(new KJControl(getHackAction(kju,"checkIn")), rtStrategy.getCheckInTime(kju));
			KJtimer.schedule(new KJControl(getHackAction(kju,"checkOut")), rtStrategy.getCheckOutTime(kju));
		}
	}
	
	public void addAllAutoUserTask(){
		List<KaiJieUser> list=kjs.getAllAtuoUser();
		for(KaiJieUser k:list){
			addAtuoTask(k);
		}
	}
	
	public Action getHackAction(KaiJieUser kju,String type){
		BasicCookieStore cookieStore = new BasicCookieStore();
		CloseableHttpClient httpclient = HttpClients.custom()
				.setDefaultCookieStore(cookieStore).build();
		Action ac=new HackLoginAction(kju.getEmployID());
		ac.setHttpClient(httpclient);
		if("checkIn".equalsIgnoreCase(type)){
			Action nextAction=new CheckInAction();
			ac.setNextAction(nextAction);
		}else{
			Action nextAction=new CheckOutAction();
			ac.setNextAction(nextAction);
		}
		return ac;
	}
	
	
	class KJControl  extends TimerTask{
		private final Logger logger = Logger.getLogger(KJControl.class);

		Action action;
		public KJControl(Action s){
			action=s;
		}
		@Override
		public void run() {
			try{
				action.mainStart();
			}catch(Exception e){
				e.printStackTrace();
				logger.error("",e);
			}finally{
				
			}
		}
	}


	@Override
	public void afterPropertiesSet() throws Exception {
		addAllAutoUserTask();
	}
}

